package com.basic.mq.handler;

import com.basic.contant.RabbitContant;
import com.basic.dto.RankingListDTO;
import com.basic.enums.RankingListStatusEnum;
import com.basic.mapper.RankingListMapper;
import com.basic.mq.MqMessageDTO;
import com.basic.mq.MqMessageHandler;
import com.basic.mq.MqMessageTypeEnum;
import com.basic.mq.dto.PublishEssayMessageDTO;
import com.basic.util.CommonUtil;
import com.basic.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

@Component
public class PublishEassyMessageHandler implements MqMessageHandler {


    final static Logger logger = LoggerFactory.getLogger(PublishEassyMessageHandler.class);

    @Autowired
    private RankingListMapper rankingListMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void deal(MqMessageDTO messageDTO) {
        logger.info("发布文章产生的消息: {}", JsonUtils.objectToJson(messageDTO));

        String message = messageDTO.getMessage();
        if(StringUtils.isEmpty(message)) {
            logger.info("发布文章产生的消息, 消息为空");
            return;
        }

        PublishEssayMessageDTO publishEssayMessageDTO;

        try {
            publishEssayMessageDTO = JsonUtils.jsonToPojo(message, PublishEssayMessageDTO.class);
            if(publishEssayMessageDTO == null) {
                logger.info("发布文章产生的消息, 消息转换为空, message:{}", message);
                return;
            }
        } catch (Exception e) {
            logger.info("发布文章产生的消息, 消息转换异常, message:{}, e:{}", message, JsonUtils.objectToJson(e));
            return;
        }

        logger.info("正式处理消息");

        RankingListDTO rankingListDTO = new RankingListDTO();
        rankingListDTO.setId(CommonUtil.createUUID());
        rankingListDTO.setEssayId(publishEssayMessageDTO.getEssayId());
        rankingListDTO.setCreateDate(new Date());
        rankingListDTO.setUpdateDate(new Date());
        rankingListDTO.setScoreHourStartDate(new Date());
        rankingListDTO.setScoreHourLast(0L);
        rankingListDTO.setScoreTotal(0L);
        rankingListDTO.setStatus(RankingListStatusEnum.NORMAL.getStatus());
        //保存
        try {
            rankingListMapper.addRankingListDTO(rankingListDTO);
        } catch (Exception e) {
            logger.error("发布文章产生的消息, 保存排行榜失败, message:{}, 异常:{}", JsonUtils.objectToJson(messageDTO), JsonUtils.objectToJson(e));
            rabbitTemplate.convertAndSend(RabbitContant.EXCHANGE_NAME, RabbitContant.ROUTING_KEY,JsonUtils.objectToJson(messageDTO));
        }
    }

    @Override
    public Integer getMessageType() {
        return MqMessageTypeEnum.PUBLISH_ESSAY.getCode();
    }
}
